package com.su.controller;

import com.alibaba.fastjson.JSON;
import com.su.dao.BookMapper;
import com.su.pojo.Book;
import com.su.pojo.BookVo;
import com.su.service.BookService;
import com.su.utils.ImportExcelUtil;
import com.su.utils.ReturnObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;


import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/book")
@CrossOrigin(origins = "*")
public class BookController {
    //通过注解进行相应的注入
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;
    @Autowired
    private BookMapper bookMapper;

    //查询所有书籍信息
    @RequestMapping("/allBook")
    @ResponseBody
    public String list(BookVo bookVo) {
        if (bookVo.getPageNum() == null) {
            bookVo.setPageNum(1);
        }
        if (bookVo.getPageSize() == null) {
            bookVo.setPageSize(5);
        }
        bookVo.setCurrentPage((bookVo.getPageNum() - 1) * bookVo.getPageSize());
        List<Book> list = bookService.getBooks(bookVo);
        int counts = bookMapper.getCounts(bookVo);
        ReturnObject returnObject = new ReturnObject();
        returnObject.setCode(0);
        returnObject.setCount(counts);
        returnObject.setList(list);
        returnObject.setMessage("查询成功");
        return JSON.toJSONString(returnObject);
    }

    //插入书籍
    @RequestMapping("/addBook")
    @ResponseBody
    public String addBook(Book books) {
        bookService.addBook(books);
        ReturnObject returnObject = new ReturnObject();
        returnObject.setCode(200);
        returnObject.setMessage("插入成功");
        returnObject.setList(null);
        returnObject.setCount(null);
        return JSON.toJSONString(returnObject);
    }

    //修改书本信息
    @RequestMapping("/updateBook")
    @ResponseBody
    public String updateBook(Book book) {
        bookService.updateBook(book);
        Book books = bookService.getBookById(book.getBookId());
        ReturnObject returnObject = new ReturnObject();
        returnObject.setCode(200);
        returnObject.setMessage("更新成功");
        returnObject.setList(null);
        returnObject.setCount(null);
        return JSON.toJSONString(returnObject);
    }

    //删除书籍
    @RequestMapping("/delBook")
    public @ResponseBody
    String del(int id) {
        bookService.deleteBookById(id);
        ReturnObject returnObject = new ReturnObject();
        returnObject.setCode(200);
        returnObject.setMessage("删除成功");
        returnObject.setList(null);
        returnObject.setCount(null);
        return JSON.toJSONString(returnObject);
    }

    //获取部门列表信息
    @RequestMapping(value = "/getBookType")
    @ResponseBody
    public String getBookType() {
        List<Integer> booktypes = bookService.getBookType();
        return JSON.toJSONString(booktypes);
    }

    //下载模板
    @RequestMapping("/downTemplate")
    public void downTemplate(HttpServletResponse response, HttpServletRequest request) throws Exception {
        String downPath = request.getServletContext().getRealPath("/") + "template" + File.separator + "批量导入模板.xlsx";
        File excelFile = new File(downPath);
        String fileName = excelFile.getName();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + new String(("下载" + fileName).getBytes("UTF-8"), "ISO8859-1"));
        response.setContentLength((int) excelFile.length());
        InputStream inputStream = new FileInputStream(excelFile);
        OutputStream outputStream = response.getOutputStream();
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.flush();
        outputStream.close();
        inputStream.close();
    }

    //实现导入功能
    @RequestMapping("/batchImportBook")
    @ResponseBody
    public String batchImportBook(HttpServletRequest request) {
        List<Book> bookList = convertExcelToBookList(request);
        int result = bookService.batchImportBook(bookList);
        ReturnObject returnObject = new ReturnObject();
        if (result > 0) {
            returnObject.setCode(1);
            returnObject.setMessage("批量插入成功");
            returnObject.setList(null);
            returnObject.setCount(result);
        } else {
            returnObject.setCode(0);
            returnObject.setMessage("批量插入失败");
            returnObject.setList(null);
            returnObject.setCount(null);
        }
        return JSON.toJSONString(returnObject);
    }

    //TODO:实现文件导出功能
    /*
    * 1.点击按钮向后端发起导出请求
    * 2.查出所有数据
    * 3.将数据封装成excel文件，并导出到浏览器
    * */
    @RequestMapping("/exportBook")
    public void exportBook(HttpServletResponse response) throws IOException {
        List<Book> bookList = bookMapper.getAllBooks();

        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("书籍列表");//设置页名
        HSSFRow row = sheet.createRow(0);
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("书籍id");
        cell = row.createCell(1);
        cell.setCellValue("书籍名称");
        cell = row.createCell(2);
        cell.setCellValue("书籍数量");
        cell = row.createCell(3);
        cell.setCellValue("书籍详情");
        cell = row.createCell(4);
        cell.setCellValue("书籍类型");
        cell = row.createCell(5);
        cell.setCellValue("入库时间");
        if(!CollectionUtils.isEmpty(bookList)){
            Book book=null;
            for (int i = 0; i <bookList.size() ; i++) {
                book=bookList.get(i);
                row=sheet.createRow(i+1);
                cell = row.createCell(0);
                cell.setCellValue(book.getBookId());
                cell = row.createCell(1);
                cell.setCellValue(book.getBookName());
                cell = row.createCell(2);
                cell.setCellValue(book.getBookCounts());
                cell = row.createCell(3);
                cell.setCellValue(book.getDetail());
                cell = row.createCell(4);
                cell.setCellValue(book.getType());
                cell = row.createCell(5);
                cell.setCellValue(book.getDate());
            }
        }

        //设置响应类型 application/octet-stream表示excel文件
        response.setContentType("application/octet-stream;charset=UTF-8");
        //设置响应头  Content-Disposition打开方式 attachment以附件的形式
        response.addHeader("Content-Disposition","attachment;filename=data.xls");
        OutputStream out = response.getOutputStream();
        wb.write(out);
        wb.close();
        out.flush();
    }


    public List<Book> convertExcelToBookList(HttpServletRequest request) {
        FileItem file = null;
        List<List<String>> data = null;
        try {
            file = ImportExcelUtil.getFileItem(request, "file");
            data = ImportExcelUtil.parse(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Book> bookList = data.stream().map(item -> {
            Book book = new Book();
            book.setBookName(item.get(0));
            book.setBookCounts(Integer.parseInt(item.get(1)));
            book.setDetail(item.get(2));
            book.setStorage(Integer.parseInt(item.get(3)));
            book.setType(Integer.parseInt(item.get(4)));
            book.setDate(new Date());
            return book;
        }).collect(Collectors.toList());
        return bookList;
    }


}
